import '../Router/MenuNav/DiyList/Scss/WeChatHomeSetUp.scss'
import { Modal, Collapse, Input, Select, Switch, Card, message, Divider } from 'antd'
import { useState, useEffect, Fragment } from 'react'
import { useBoolean, useEventEmitter, useRequest, useSetState } from 'ahooks'
import { Http } from '../Api'
import { WeChatModuleList, WeChatModule, WeChatModuleDefault, ModuleTitle001 } from './WeChatModule'
import {
    // WeChatImageUrl,
    WeChatMenuListArr,
    WeChatUIThemeList,
    WeChatAntdThemeList,
    WeChatChinaThemeList,
    WeChatMenuItemTopStyle,
    MenuItemTopStyle001,
} from './WeChatCommon'

import { colorCount } from './Common'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { SetUpCommonModal } from './SetUpModal'
import GridLayout from 'react-grid-layout'
import uuid from 'react-uuid'

const WeChatMenuItemTopStyleArr = {
    MenuItemTopStyle001,
}

const { Panel } = Collapse
const { TextArea } = Input
const { Meta } = Card

// 预览样式
const Preview = ({ data, MenuItemSetUp, theme, TabsActiveEvent, SubmitDataEvent }) => {
    const {
        WeChatMenuItemTopStyleSelect,
        WeChatMenuItemTopTitle,
        WeChatMenuItemTopEnglish,
        WeChatMenuItemTopStatus,
        WeChatMenuItemTabsList,
        WeChatMenuItemTabsDetails,
        WeChatMenuItemTabsDispose,
        WeChatMenuItemTopShifting,
    } = MenuItemSetUp

    const [TabsActive, setTabsActive] = useState()

    useEffect(() => {
        if (WeChatMenuItemTabsList.length !== 0) {
            const [{ uuid }] = WeChatMenuItemTabsList
            TabsActiveEvent.emit(uuid)
            setTabsActive(uuid)
        }
    }, [TabsActiveEvent, WeChatMenuItemTabsList])

    const color = WeChatUIThemeList[theme] || WeChatAntdThemeList[theme] || WeChatChinaThemeList[theme]
    const submitMenuList = () => SubmitDataEvent.emit(MenuItemSetUp)

    return (
        <div className="Preview">
            <div className="WeChat">
                {(() => {
                    const extra = ['8f335f19-b79e-4588-b7ae-82713d7aff68']
                    const Template = WeChatMenuItemTopStyleArr[WeChatMenuItemTopStyleSelect]
                    return (
                        <Template
                            extra={extra.indexOf(data.uuid) !== -1 ? true : false}
                            theme={color}
                            title={WeChatMenuItemTopTitle}
                            english={WeChatMenuItemTopEnglish}
                            status={WeChatMenuItemTopStatus}
                        />
                    )
                })()}
                {WeChatMenuItemTabsList.length > 1 && (
                    <div className="WeChatTabs" style={{ background: color }}>
                        {WeChatMenuItemTabsList.map(({ uuid, title }) => (
                            <div
                                key={uuid}
                                className={TabsActive === uuid ? 'active' : ''}
                                onClick={() => {
                                    setTabsActive(uuid)
                                    TabsActiveEvent.emit(uuid)
                                }}
                            >
                                {title}
                            </div>
                        ))}
                    </div>
                )}
                <div className="WeChatModuleList" style={WeChatMenuItemTopShifting ? { marginTop: -36 } : {}}>
                    {WeChatMenuItemTabsDetails[TabsActive] &&
                        WeChatMenuItemTabsDetails[TabsActive].length !== 0 &&
                        WeChatMenuItemTabsDetails[TabsActive].map(({ i, x, y, w, h }, index) => {
                            const [title, uuid] = i.split('_')
                            const Template = WeChatModule[title]
                            const data = WeChatMenuItemTabsDispose[TabsActive][uuid]
                            return (
                                <div key={i} style={{ gridArea: `${y + 1}/${x + 1}/${y + h}/${w + x + 1}` }}>
                                    <ModuleTitle001 data={data} back={color} />
                                    {!data.status && <div style={{ height: 20 }} />}
                                    <Template ModuleItemEvent={false} data={data} />
                                </div>
                            )
                        })}
                </div>
            </div>
            <div
                className="Submit"
                style={{ background: color, '--hsl': colorCount(color || '#fff') + '%' }}
                onClick={submitMenuList}
            >
                保存设置
            </div>
        </div>
    )
}

// 头部设置
const TopSetUp = ({ MenuItemSetUpEvent, MenuItemSetUp }) => {
    const {
        WeChatMenuItemTopStyleSelect,
        WeChatMenuItemTopTitle,
        WeChatMenuItemTopEnglish,
        WeChatMenuItemTopStatus,
        WeChatMenuItemTopShifting,
    } = MenuItemSetUp

    return (
        <div className="TopSetUp">
            <div className="entry">
                <div>样式选择 : </div>
                <Select
                    placeholder="请选择页面路径"
                    options={WeChatMenuItemTopStyle}
                    value={WeChatMenuItemTopStyleSelect}
                    onChange={e => {
                        MenuItemSetUpEvent.emit({ WeChatMenuItemTopStyleSelect: e })
                    }}
                />
            </div>

            <div className="entry">
                <div>菜单名称 : </div>
                <Input
                    placeholder="请输入菜单名称"
                    value={WeChatMenuItemTopTitle}
                    onChange={e => MenuItemSetUpEvent.emit({ WeChatMenuItemTopTitle: e.target.value })}
                />
            </div>

            <div className="entry">
                <div>菜单engList : </div>
                <TextArea
                    autoSize
                    placeholder="请输入菜单engList"
                    value={WeChatMenuItemTopEnglish}
                    onChange={e => MenuItemSetUpEvent.emit({ WeChatMenuItemTopEnglish: e.target.value })}
                />
            </div>

            <div className="entry">
                <div>多项目 : </div>
                <div>
                    <Switch
                        checkedChildren="开启"
                        unCheckedChildren="关闭"
                        checked={WeChatMenuItemTopStatus}
                        onChange={e => MenuItemSetUpEvent.emit({ WeChatMenuItemTopStatus: e })}
                    />
                </div>
            </div>
            <div className="entry">
                <div>向上偏移 : </div>
                <div>
                    <Switch
                        checkedChildren="开启"
                        unCheckedChildren="关闭"
                        checked={WeChatMenuItemTopShifting}
                        onChange={e => MenuItemSetUpEvent.emit({ WeChatMenuItemTopShifting: e })}
                    />
                </div>
            </div>
        </div>
    )
}

// TABS设置
const TabsSetUp = ({ theme, MenuItemSetUpEvent, MenuItemSetUp }) => {
    const color = WeChatUIThemeList[theme] || WeChatAntdThemeList[theme] || WeChatChinaThemeList[theme]
    const { WeChatMenuItemTabsList, WeChatMenuItemTabsDetails, WeChatMenuItemTabsDispose } = MenuItemSetUp
    const [ModalStatus, { setTrue, setFalse }] = useBoolean(false)
    const [ModelTitles, setModelTitles] = useState()
    const [ModalTabUuid, setModalTabUuid] = useState()
    const SetUpCommonModalEvent = useEventEmitter()
    SetUpCommonModalEvent.useSubscription(val => {
        if (val.newUuid) {
            MenuItemSetUpEvent.emit({ WeChatMenuItemTabsDetails: { ...WeChatMenuItemTabsDetails, [val.newUuid]: [] } })
            MenuItemSetUpEvent.emit({ WeChatMenuItemTabsDispose: { ...WeChatMenuItemTabsDispose, [val.newUuid]: {} } })
        }
        MenuItemSetUpEvent.emit({ WeChatMenuItemTabsList: val.list })
    })

    const AddTabs = () => {
        setModelTitles('新增TABS')
        setModalTabUuid()
        setTrue()
    }

    const ModifyTabs = uuid => {
        setModelTitles('修改TABS')
        setModalTabUuid(uuid)
        setTrue()
    }

    const DeleteTabs = uuid => {
        if (WeChatMenuItemTabsList.length === 1) return message.warning('必须保留一条Tabs')
        let data = WeChatMenuItemTabsList
        data.splice(
            WeChatMenuItemTabsList.findIndex(v => v.uuid === uuid),
            1,
        )
        MenuItemSetUpEvent.emit({ WeChatMenuItemTabsList: data })
    }

    return (
        <div className="TabsSetUp">
            <div className="List">
                <div
                    className="Add"
                    style={{ background: color, '--hsl': colorCount(color || '#fff') + '%' }}
                    onClick={AddTabs}
                >
                    新增
                </div>
                <div className="ListItem">
                    {WeChatMenuItemTabsList.map(({ uuid, title }) => (
                        <Card
                            key={uuid}
                            actions={[
                                <EditOutlined key="edit" onClick={() => ModifyTabs(uuid)} />,
                                <DeleteOutlined
                                    key="delete"
                                    style={{ color: 'red' }}
                                    onClick={() => DeleteTabs(uuid)}
                                />,
                            ]}
                        >
                            <Meta onClick={() => console.log('选中uuid', uuid)} title={title} />
                        </Card>
                    ))}
                </div>
            </div>

            {/* 添加tabs */}
            {ModalStatus && (
                <SetUpCommonModal
                    title={ModelTitles}
                    Off={setFalse}
                    data={{
                        type: 'MenuItemTabsOptions',
                        theme: color,
                        list: WeChatMenuItemTabsList,
                        uuid: ModalTabUuid,
                        // active: Caption,
                        // key: 'Caption',
                    }}
                    SetUpCommonModalEvent={SetUpCommonModalEvent}
                />
            )}
        </div>
    )
}

// TABS详情
const TabsDetailed = ({ theme, TabsDetailedUuid, MenuItemSetUpEvent, MenuItemSetUp }) => {
    const color = WeChatUIThemeList[theme] || WeChatAntdThemeList[theme] || WeChatChinaThemeList[theme]
    const { WeChatMenuItemTabsDetails, WeChatMenuItemTabsDispose } = MenuItemSetUp

    const [ModuleItem, setModuleItem] = useState()

    const ModuleItemEvent = useEventEmitter()
    ModuleItemEvent.useSubscription(val => setModuleItem(val))

    const [ModuleStatus, { setTrue, setFalse }] = useBoolean(false)
    const [ModuleUuid, setModuleUuid] = useState()
    const [DisPoseData, setDisPoseData] = useState()

    const modifyItem = i => {
        const uuid = i.split('_')[1]
        const DisPoseData = WeChatMenuItemTabsDispose[TabsDetailedUuid][uuid]
        setDisPoseData(DisPoseData)
        setModuleUuid(i)
        setTrue()
    }
    const deleteItem = i => {
        const data = JSON.parse(JSON.stringify(WeChatMenuItemTabsDetails[TabsDetailedUuid]))
        data.splice(
            WeChatMenuItemTabsDetails[TabsDetailedUuid].findIndex(v => v.i === i),
            1,
        )
        MenuItemSetUpEventEmit(data)
    }

    const MenuItemSetUpEventEmit = data => {
        WeChatMenuItemTabsDetails[TabsDetailedUuid] = data
        MenuItemSetUpEvent.emit({ WeChatMenuItemTabsDetails })
    }

    const SetUpCommonModalEvent = useEventEmitter()
    SetUpCommonModalEvent.useSubscription(val => {
        const { active, uuid, DisPoseData } = val
        WeChatMenuItemTabsDispose[active][uuid] = DisPoseData
        MenuItemSetUpEvent.emit({ WeChatMenuItemTabsDispose })
    })

    return (
        <div className="TabsSetUp">
            <div className="Page">
                <GridLayout
                    className="layout"
                    layout={WeChatMenuItemTabsDetails[TabsDetailedUuid]}
                    margin={[15, 0]}
                    cols={1}
                    width={375}
                    rowHeight={1}
                    isDroppable={true}
                    isResizable={true}
                    onDrop={e => {
                        let NewBox = e.findIndex(v => v.i === '__dropping-elem__')
                        const UUID = uuid()
                        e[NewBox] = { ...e[NewBox], i: `${ModuleItem}_${UUID}`, h: WeChatModuleDefault[ModuleItem].h }
                        const list = {
                            ...WeChatMenuItemTabsDispose[TabsDetailedUuid],
                            [UUID]: WeChatModuleDefault[ModuleItem],
                        }
                        WeChatMenuItemTabsDispose[TabsDetailedUuid] = list
                        MenuItemSetUpEvent.emit({ WeChatMenuItemTabsDispose })
                        MenuItemSetUpEventEmit(e)
                    }}
                    onResizeStop={e => MenuItemSetUpEventEmit(e)}
                    onDragStop={e => MenuItemSetUpEventEmit(e)}
                >
                    {WeChatMenuItemTabsDetails[TabsDetailedUuid] &&
                        WeChatMenuItemTabsDetails[TabsDetailedUuid].map(({ i }) => {
                            const [title, uuid] = i.split('_')
                            const Template = WeChatModule[title]
                            const data = WeChatMenuItemTabsDispose[TabsDetailedUuid][uuid]
                            return (
                                <div className="ModuleItemBox" key={i}>
                                    <ModuleTitle001 data={data} back={color} />
                                    <Template ModuleItemEvent={false} data={data} />
                                    <div className="ModuleItemBoxOptions">
                                        <div
                                            style={{ '--color': color, '--hsl': colorCount(color || '#fff') + '%' }}
                                            onClick={() => modifyItem(i)}
                                        >
                                            <span></span>
                                            <span></span>
                                            <span></span>
                                            <span></span>
                                            配置
                                        </div>
                                        <div
                                            style={{ '--color': '#eb261a', '--hsl': colorCount('#eb261a') + '%' }}
                                            onClick={() => deleteItem(i)}
                                        >
                                            <span></span>
                                            <span></span>
                                            <span></span>
                                            <span></span>
                                            删除
                                        </div>
                                    </div>
                                </div>
                            )
                        })}
                </GridLayout>
            </div>
            <div className="Modal">
                {WeChatModuleList.map(({ uuid, title, content, children }) => (
                    <div key={uuid}>
                        <Divider> {title}</Divider>
                        {children.map((item, index) => {
                            const Template = WeChatModule[item]
                            const data = WeChatModuleDefault[item]
                            return (
                                <Fragment key={index}>
                                    {content && <div className="ModuleTitle">{content[index]} </div>}
                                    <Template ModuleItemEvent={ModuleItemEvent} data={data} />
                                </Fragment>
                            )
                        })}
                    </div>
                ))}
            </div>
            {ModuleStatus && (
                <SetUpCommonModal
                    title="修改配置参数"
                    Off={setFalse}
                    data={{
                        type: 'MenuItemTabsDispose',
                        theme: color,
                        module: ModuleUuid,
                        active: TabsDetailedUuid,
                        disPose: DisPoseData,
                    }}
                    SetUpCommonModalEvent={SetUpCommonModalEvent}
                />
            )}
        </div>
    )
}

export const WeChatMenuItem = ({ Off, data }) => {
    const { tableName } = data
    const [theme, setTheme] = useState()

    const [TabsDetailedUuid, setTabsDetailedUuid] = useState()

    const { runAsync: getSmallProgramConfig } = useRequest(Http, {
        manual: true,
        onSuccess: res => setTheme(JSON.parse(res[0].menus).theme),
    })

    const { runAsync: getJsonInfoByUuid } = useRequest(Http, {
        manual: true,
        onSuccess: res => setMenuItemSetUp(res),
    })

    const { runAsync: posSaveJsonInfoByUuid } = useRequest(Http, {
        manual: true,
        onSuccess: () => message.success('菜单保存成功!'),
    })

    useEffect(() => {
        getSmallProgramConfig({ url: 'getSmallProgramConfig' })
        getJsonInfoByUuid({ url: 'getJsonInfoByUuid', data: { uuid: data.uuid } })
    }, [getSmallProgramConfig, getJsonInfoByUuid, data])

    const [MenuItemSetUp, setMenuItemSetUp] = useSetState({
        WeChatMenuItemTopStyleSelect: 'MenuItemTopStyle001',
        WeChatMenuItemTopTitle: '',
        WeChatMenuItemTopEnglish: '',
        WeChatMenuItemTopStatus: false,
        WeChatMenuItemTopShifting: false,
        WeChatMenuItemTabsList: [],
        WeChatMenuItemTabsDetails: {},
        WeChatMenuItemTabsDispose: {},
    })

    const MenuItemSetUpEvent = useEventEmitter()
    MenuItemSetUpEvent.useSubscription(val => setMenuItemSetUp(val))
    const TabsActiveEvent = useEventEmitter()
    TabsActiveEvent.useSubscription(val => setTabsDetailedUuid(val))

    const SubmitDataEvent = useEventEmitter()
    SubmitDataEvent.useSubscription(val => {
        posSaveJsonInfoByUuid({
            url: 'posSaveJsonInfoByUuid',
            data: JSON.stringify(JSON.stringify(val)),
            path: [data.uuid],
        })
    })

    useEffect(() => {
        if (!data.MenuItemSetUp) {
            const Uuid = uuid()
            setMenuItemSetUp({
                WeChatMenuItemTopTitle: WeChatMenuListArr.find(v => v.uuid === data.uuid).tableName,
                WeChatMenuItemTopEnglish: WeChatMenuListArr.find(v => v.uuid === data.uuid).english,
                WeChatMenuItemTabsList: [{ uuid: Uuid, sortId: 1, title: '默认Tabs' }],
                WeChatMenuItemTabsDetails: { [Uuid]: [] },
                WeChatMenuItemTabsDispose: { [Uuid]: {} },
            })
        }
    }, [data, setMenuItemSetUp])

    return (
        <Modal
            className="ModalBox"
            open={true}
            footer={null}
            maskClosable={false}
            onCancel={Off}
            destroyOnClose
            title={`WeChat${tableName}配置`}
            centered
            width="80vw"
        >
            <div className="WeChatMenuItem">
                <Preview
                    data={data}
                    theme={theme}
                    MenuItemSetUp={MenuItemSetUp}
                    TabsActiveEvent={TabsActiveEvent}
                    SubmitDataEvent={SubmitDataEvent}
                />
                <div className="dispose">
                    <Collapse accordion>
                        <Panel header="头部设置" key="1">
                            <TopSetUp MenuItemSetUpEvent={MenuItemSetUpEvent} MenuItemSetUp={MenuItemSetUp} />
                        </Panel>
                        <Panel header="TABS设置" key="2">
                            <TabsSetUp
                                theme={theme}
                                MenuItemSetUpEvent={MenuItemSetUpEvent}
                                MenuItemSetUp={MenuItemSetUp}
                            />
                        </Panel>
                        <Panel header="TABS详情" key="3">
                            <TabsDetailed
                                theme={theme}
                                MenuItemSetUpEvent={MenuItemSetUpEvent}
                                TabsDetailedUuid={TabsDetailedUuid}
                                MenuItemSetUp={MenuItemSetUp}
                            />
                        </Panel>
                    </Collapse>
                </div>
            </div>
        </Modal>
    )
}
